import axios, { AxiosError, type AxiosRequestHeaders, type AxiosResponse } from 'axios'
// @ts-ignore
import qs from 'qs'
import { http_config } from './config'
import mpAdapter from 'axios-miniprogram-adapter'

// @ts-ignore
axios.defaults.adapter = mpAdapter
const { request_timeout } = http_config

export const PATH_URL = 'https://apis.netstart.cn/bcomic'
// 创建axios实例
const service: any = axios.create({
    baseURL: PATH_URL, // api 的 base_url
    timeout: request_timeout // 请求超时时间
})


//显示loading
function showLoading(title: any) {
    uni.showToast({
        title: title,
        duration:0,
    })
}

//隐藏loading
function hideLoading() {
    uni.hideToast();
}


// request拦截器
service.interceptors.request.use(
    (config: any) => {
        if (config.showLoading) {
            showLoading(config.message);
        }
        if (
            config.method === 'post' &&
            (config.headers as AxiosRequestHeaders)['Content-Type'] ===
            'application/x-www-form-urlencoded'
        ) {
            config.data = qs.stringify(config.data)
        }
        // get参数编码
        if (config.method === 'get' && config.params) {
            let url = config.url as string
            url += '?'
            const keys = Object.keys(config.params)
            for (const key of keys) {
                if (config.params[key] !== void 0 && config.params[key] !== null) {
                    url += `${key}=${encodeURIComponent(config.params[key])}&`
                }
            }
            url = url.substring(0, url.length - 1)
            config.params = {}
            config.url = url
        }

        return config
    },
    (error: AxiosError) => {
        console.log(error) // for debug
        uni.showToast({
            title: error.message,
            icon: 'none'
        })
        Promise.reject(error)
        hideLoading();
    }
)

// response 拦截器
service.interceptors.response.use(
    (response: AxiosResponse<any>) => {
        hideLoading();
        if (response.config.responseType === 'blob') {
            // 如果是文件流，直接过
            return response
        } else {
            if (response.config.responseType === 'arraybuffer') {
                return response.data = `data: image/jpeg;base64,${btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))}`
            } else {
                const { success, code, msg } = response.data;
                if (!success) {
                    // 规定错误码功能，例如9108-请登录系统进行访问,自动跳转登录页
                    if (code == 9108) {
                        // 请登录系统进行访问,自动跳转登录页
                        uni.showToast({
                            title: '登录过期请重新登录'
                        })
                        setTimeout(() => {
                            uni.reLaunch({
                                url: '/pages/login/login'
                            })
                        }, 2000);
                    }
                    return response.data
                }
                return response.data;
            }
        }
    }
    ,
    (error: AxiosError) => {
        console.log('err' + error) // for debug
        uni.showToast({
            title: error.message,
            icon: 'none'
        })
        hideLoading();
        return Promise.reject(error)
    }
)

export { service }